<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/4
 * Time: 15:25
 */

namespace app\api\service;


class Wechat
{
    const APPID = 'wx6d360ceb6201c975';
    const SECRET = '332ae587ca1a38646b8e67341ec5e924';

    //获取access_token
    public function getAccessToken($code)
    {
        //GET请求
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . self::APPID . '&secret=' . self::SECRET . '&code=' . $code . '&grant_type=authorization_code';
        $res = curl_get($url);
        $res = json_decode($res, true);
        if (!isset($res['errcode'])) {
            return $res;
        }
        return false;
    }

    //刷新access_token
    public function refreshAccessToken($refresh_token)
    {
        //GET请求
        $url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . self::APPID . '&grant_type=refresh_token&refresh_token=' . $refresh_token;
        $res = curl_get($url);
        $res = json_decode($res, true);
        if (!isset($res['errcode'])) {
            return $res;
        }
    }

    //验证access_token
    public function checkAccessToken($access_token,$openid)
    {
        //GET请求
        $url = 'https://api.weixin.qq.com/sns/auth?access_token=' . $access_token . '&openid=' . $openid;
        $res = curl_get($url);
        $res = json_decode($res, true);
        if ($res['errcode'] == 0) {
            return true;
        }else{
            return false;
        }
    }

    //获取用户个人信息
    public function getUserInfo($access_token,$openid)
    {
        //GET请求
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid;
        $res = curl_get($url);
        $res = json_decode($res, true);
        if (!isset($res['errcode'])) {
            return $res;
        }
    }


    //获取微信信息
    public function getInfo($code)
    {
        $res = $this->getAccessToken($code);
        if (!$res) {
            return false;
        }
        $openid = $res['openid'];
        $access_token = $res['access_token'];
        $refresh_token = $res['refresh_token'];
        //检测access_token是否可用
        $check_token = $this->checkAccessToken($access_token, $openid);
        if (!$check_token) {
            $refresh_res = $this->refreshAccessToken($refresh_token);
            $openid = $refresh_res['openid'];
            $access_token = $refresh_res['access_token'];
        }
        $user_info = $this->getUserInfo($access_token, $openid);
        return $user_info;
    }


}